package club.cearnach.api.security.service;

import club.cearnach.api.dao.IUserDao;
import club.cearnach.core.property.MovieSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 前台用户登录验证
 *
 * @author 阮胜
 * @date 2018/5/25 23:35
 */
@Component
@Slf4j
@Qualifier("normalUserDetailService")
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private MovieSecurityProperties movieSecurityProperties;
    private final IUserDao userDao;

    public UserDetailServiceImpl(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        club.cearnach.entity.User user = userDao.findByAccount(username)
                .orElseThrow(() -> new UsernameNotFoundException("找不到指定的用户"));
        List<GrantedAuthority> authorities = AuthorityUtils
                .commaSeparatedStringToAuthorityList(
                        movieSecurityProperties.getRolePrefix().concat(user.getRole().getName()));
        return new User(user.getAccount(), user.getPassword(), authorities);
    }
}
